package com.hongdee.base.carconfigure.service.impl;

import com.hongdee.base.Common;
import com.hongdee.base.basedao.impl.BaseDaoImpl;
import com.hongdee.base.carconfigure.dao.ICarConfigureDao;
import com.hongdee.base.carconfigure.entity.TBcCarConfigure;
import com.hongdee.base.carconfigure.service.ICarConfigureService;
import com.hongdee.base.carmodel.entity.TBcCarModel;
import com.hongdee.common.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 名  称:CarConfigureDaoImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.base.carconfigure.service.impl
 * 作  者: 术洪超
 * 日  期:2017-05-18 11:18
 */
@Service
public class CarConfigureServiceImpl implements ICarConfigureService {

    String tabName = "T_BC_CARCONFIGURE";
    String entityName = "TBcCarConfigure";

    @Autowired
    private ICarConfigureDao iCarConfigureDao;


    //查询配置
    private List CarConfigure(String carModelId,String bCode) throws Exception {
        return this.iCarConfigureDao.list("select * from t_bc_carConfigure where model_id = ? and brand_code = ? ", carModelId,bCode);
    }


    private Map querySeries(String modelId) throws Exception {

        List params = new ArrayList();
        String sql = "select series_id from t_bc_carModel where id = ? limit 1";
        params.add(modelId);

        return this.iCarConfigureDao.info(sql, params.toArray());
    }


    private Map queryBrand(String seriesId) throws Exception {
        List params = new ArrayList();
        String sql = "select brand_code from t_bc_car_series where id = ? limit 1";
        params.add(seriesId);
        return this.iCarConfigureDao.info(sql, params.toArray());


    }


    /**
     * @param carModelId 车型ID
     * @return List<Map>
     * @throws Exception
     * @desc 查询详情
     * @author 术洪超
     */
    @Override
    public List<Map> buildTreeNodeList(String carModelId,String bCode) throws Exception {

        List<Map> allConfigure = CarConfigure(carModelId,bCode);
        List<Map> all = new ArrayList<>();

        for (Map tempS : allConfigure) {
            Map mapConfigure = new HashMap();
            mapConfigure.put("label", tempS.get("configureName"));
            mapConfigure.put("value", tempS.get("id"));
            mapConfigure.put("code",tempS.get("configureCode"));
            //配置
            mapConfigure.put("type", "3");
            all.add(mapConfigure);
        }
        return all;
    }

    /**
     * @param data 要保存的变更历史记录实体
     * @return Map
     * @throws Exception
     * @desc 保存添加或者修改的实体内容，通过主键判断
     * @author 术洪超
     */
    @Override
    public TBcCarConfigure saveOrUpdate(TBcCarConfigure data, String uid) throws Exception {

        if (data.getConfigureCode() == null||data.getConfigureCode().equals("")) {
            throw new Exception("配置编码不能为空！");
        }
        if (data.getConfigureName() == null||data.getConfigureName().equals("")) {
            throw new Exception("配置名称不能为空！");
        }
        if(data.getVinCode()==null||data.getVinCode().equals("")){
            throw new Exception("vin识配码不能为空！");
        }
        if (data.getId() == null) {
           if (existConfigureCode(data.getConfigureCode(),data.getModelId())) {
               throw new Exception("配置编码已存在！");
           }else{
               //添加配置代码的正则表达式
               data.setConfigureRegularCode(this.regularCode(data.getConfigureCode()));
           }

           if (existConfigureName(data.getConfigureName(),data.getModelId())) {
               throw new Exception("配置名称已存在！");
           }

           if (existConfigureVinCode(data.getVinCode())) {
               throw new Exception("vin识配码已存在！");
           }

         data.setCreateUser(uid);
         data.setCreateTime(Calendar.getInstance().getTimeInMillis());
         data.setResStatus("1");

         Map mapSeries = this.querySeries(data.getModelId());
         Map mapBrand = new HashMap();
         if(mapSeries.size()>0){
             mapBrand = this.queryBrand(mapSeries.get("seriesId").toString());
         }
         if(mapBrand.size()>0){
             data.setBrandCode(mapBrand.get("brandCode").toString());
         }
         data.setDependOnModel("0");//依赖车型
        } else {
           Map map = this.iCarConfigureDao.info("select * from T_BC_CARCONFIGURE where id=?",data.getId());

           if(!data.getConfigureCode().equals(map.get("configureCode"))){
               if (existConfigureCode(data.getConfigureCode(),data.getModelId())) {
                   throw new Exception("配置编码已存在！");
               }else{
                   //添加配置代码的正则表达式
                   data.setConfigureRegularCode(this.regularCode(data.getConfigureCode()));
               }
           }
           if(!data.getConfigureName().equals(map.get("configureName"))){
               if (existConfigureName(data.getConfigureName(),data.getModelId())) {
                   throw new Exception("配置名称已存在！");
               }
           }
           if(!data.getVinCode().equals(map.get("vinCode"))){
               if (existConfigureVinCode(data.getVinCode())) {
                   throw new Exception("vin识配码已存在！");
               }
           }
            data.setUpdateUser(uid);
            data.setUpdateTime(Calendar.getInstance().getTimeInMillis());
        }
        this.iCarConfigureDao.saveOrUpdate(data);
        return data;
    }


    /**
     * @param id     主键 ID
     * @param status 状态
     * @return
     * @throws Exception
     * @desc 修改状态
     * @author 术洪超
     */

    @Override
    public void update(String id, String status) throws Exception {

        Map map = new HashMap();
        String hql = "update " + entityName + " set resStatus =:status where id =:id";
        map.put("status", status);
        map.put("id", id);
        this.iCarConfigureDao.update(hql, map);

    }


    /**
     * @param id 主键
     * @return Map
     * @throws Exception
     * @desc 配置详细
     * @author 术洪超
     */
    @Override
    public Map info(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择配置！");
        }
        List params = new ArrayList();
        String sql = "select * from " + tabName + " where id = ? ";
        params.add(id);
        return this.iCarConfigureDao.info(sql, params.toArray());
    }

    /**
     * @param start   起始记录
     * @param limit   页面大小
     * @param modelId 车型ID
     * @return Map
     * @throws Exception
     * @desc 通过 JDBCDao分页查询
     * @author 术洪超
     */

    @Override
    public Map page(String start, String limit, String modelId, String configureCode) throws Exception {

        StringBuffer sql = new StringBuffer();
        sql.append("select * from " + tabName);

        List params = new ArrayList();

        Common common = new Common();
        Boolean hasWhere = false;

        if (!StringUtils.isEmpty(configureCode)) {

            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" configure_code like ? ");
            params.add("%" + configureCode + "%");
        }

        if (!StringUtils.isEmpty(modelId)) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" model_id = ? ");
            params.add(modelId);
        }
        return this.iCarConfigureDao.page(sql.toString(), params.toArray(), start, limit);

    }

    @Override
    public List<Map> combo(String modelId) throws Exception {
        List params = new ArrayList();
        String sql = " select * from " + tabName + " where model_id = ? and res_status = '1' order by create_time desc";
        params.add(modelId);
        List<Map<String, Object>> mapList = this.iCarConfigureDao.list(sql, params.toArray());
        List<Map> resList = new ArrayList<Map>();
        Map temp;
        for (Map map : mapList) {
            temp = new HashMap();
            temp.put("value", map.get("id"));
            temp.put("code",map.get("configureName"));
            temp.put("label", map.get("configureName"));
            resList.add(temp);
        }
        return resList;
    }

    @Override
    public TBcCarConfigure getInfo(String id) throws Exception {
        return this.iCarConfigureDao.info(id);
    }

    //判断配置编码是否存在

    private boolean existConfigureCode(String configureCode,String modelId) throws Exception {

        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = true;

        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName +" where model_id= ? ");
        params.add(modelId);

        if (!configureCode.isEmpty() && !configureCode.equals("")) {
            hasWhere = common.appendWhereIfNeed(sb, hasWhere);
            sb.append(" configure_code = ? ");
            params.add(configureCode);
        }

        Map map = this.iCarConfigureDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }

    //判断配置名称是否存在
    private boolean existConfigureName(String configureName,String modelId) throws Exception {

        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = true;

        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName+" where model_id = ?");
        params.add(modelId);
        if (!configureName.isEmpty() && !configureName.equals("")) {
            hasWhere = common.appendWhereIfNeed(sb, hasWhere);
            sb.append(" configure_name = ? ");
            params.add(configureName);
        }

        Map map = this.iCarConfigureDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }


    //判断车型识配码是否存在
    private boolean existConfigureVinCode(String vinCode) throws Exception {

        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName);

        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = false;
        if (!vinCode.isEmpty() && !vinCode.equals("vinCode")) {
            hasWhere = common.appendWhereIfNeed(sb, hasWhere);
            sb.append(" vin_code = ? ");
            params.add(vinCode);
        }

        Map map = this.iCarConfigureDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }

    /**
     * 转换正则表达式
     * @param configureName
     * @return
     * @throws Exception
     */
    private String regularCode(String configureName) throws Exception{

        StringBuffer configureCode = new StringBuffer();
        configureCode.append("^"+configureName);

        if(configureCode.indexOf("(")!=-1){
            configureCode.insert(configureCode.indexOf("("),"\\");
        }else if (configureCode.indexOf("（")!=-1){
            configureCode.insert(configureCode.indexOf("（"),"\\");
        }

        if(configureCode.indexOf(")")!=-1){
            configureCode.insert(configureCode.indexOf(")"),"\\");
        }else if(configureCode.indexOf("）")!=-1){
            configureCode.insert(configureCode.indexOf("）"),"\\");
        }

        if(configureCode.indexOf("[")!=-1){
            configureCode.insert(configureCode.indexOf("["),"\\");
        }
        if(configureCode.indexOf("]")!=-1){
            configureCode.insert(configureCode.indexOf("]"),"\\");
        }

        configureCode.append("$");
        return  configureCode.toString();
    }

    /**
     * @param carModelId 车型ID
     * @return List<Map>
     * @throws Exception
     * @desc 查询详情
     * @author 术洪超*/
    //@Override
   /* public List<Map> buildTreeNodeList(String carModelId,String bCode) throws Exception {

        List<Map> allConfigure = CarConfigure(carModelId,bCode);
        List<Map> all = new ArrayList<>();

        for (Map tempS : allConfigure) {
            Map mapConfigure = new HashMap();
            mapConfigure.put("label", tempS.get("configureName"));
            mapConfigure.put("value", tempS.get("id"));
            mapConfigure.put("code",tempS.get("configureCode"));
            //配置
            mapConfigure.put("type", "3");
            all.add(mapConfigure);
        }
        return all;
    }*/

}
